import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Upload,
	message,
	TreeSelect,
	InputNumber,
} from 'antd'
import React, {useState, useEffect} from 'react'
import {connect, history, useModel} from 'umi'
import type {UploadFile} from 'antd/es/upload/interface'
import {ProColumns, EditableProTable} from '@ant-design/pro-components'
import styles from './index.less'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'
import {
	allocationnoInfo,
	editAllocationno,
	getCostList,
} from '@/service/storage/allocation'
import Modal from '@/components/Modal'
import {getCompany} from '@/service/common'
import {translateDataToTree} from '@/utils/common'
import AllocateVehicles from '../../components/AllocateVehicles'
import OperationRecord from '@/components/OperationRecord'
import {getCompanyScope} from '@/service/system/company'

const {TextArea} = Input

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const edit = (props: any) => {
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const {query} = props.location
	const [form] = Form.useForm()
	const [basicsForm] = Form.useForm()
	const [costForm] = Form.useForm()
	const [cancelForm] = Form.useForm()
	const [type, setType] = useState<string>()
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [formData, setFormData] = useState<any>({})
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [inCompanyData, setInCompanyData] = useState([])
	const [companyData, setCompanyData] = useState([])
	const [costData, setCostData] = useState<any>([])
	const [detailsData, setDetailsData] = useState<any>()
	const [columns, setColumns] = useState<any>()
	const [editableKeys, setEditableRowKeys] = useState<any>([])
	const [costList, setCostList] = useState<any[]>([])
	const [btnLoading, setBtnLoading] = useState(false)
	const [status, setStatus] = useState('')

	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	/** 获取调入公司数据 */
	const onInCompany = () => {
		getCompanyScope().then((res: any) => {
			const list = translateDataToTree(res.data)
			setInCompanyData(list as any)
		})
	}
	/** 获取配置费用项数据 */
	const onCost = () => {
		getCostList({status: 2, businessType: 4, current: 1, size: 100})
			.then((res: any) => {
				const column: ProColumns<any>[] = [
					{
						title: '项目',
						dataIndex: '项目',
						width: 120,
						readonly: true,
					},
				]
				if (res?.success) {
					res?.data?.records?.forEach(
						(item: {expenseItemName: any}) => {
							column.push({
								title: item?.expenseItemName,
								dataIndex: item?.expenseItemName,
								width: 120,
								renderFormItem: (text: any, {record}) => (
									<InputNumber
										style={{width: '100%'}}
										max={9999999}
										step="0.01"
										onBlur={(e) => {
											let num = 0
											const arr = []
											const newData = {...record}
											const cost = Number(e.target.value)
											if (
												Number.isNaN(cost) ||
												cost < 0
											) {
												newData[text.title] = '0'
												message.warning(
													'请填写正确的费用项，且费用项不能小于0',
												)
											} else {
												newData[text.title] =
													cost?.toFixed(2)
											}
											Object.keys(newData)?.forEach(
												(items) => {
													if (
														items !== '项目' &&
														items !== 'key' &&
														items !== '合计' &&
														Number(
															newData[items],
														).toString() !== 'NaN'
													) {
														num += Number(
															newData[items],
														)
														arr.push({
															costName: items,
															amount: newData[
																items
															],
														})
													}
												},
											)
											arr.push({
												costName: '合计',
												amount: num?.toFixed(2),
											})
											setCostList(arr)
											newData['合计'] = num?.toFixed(2)
											newData.key = (
												Math.random() * 1000000
											).toFixed(0)
											const hrefs = window.location.href
											if (hrefs.includes('edit')) {
												setEditableRowKeys([
													newData?.key,
												])
											}
											setCostData([newData])
										}}
									/>
								),
							})
						},
					)
				}
				column.push({
					title: '合计',
					dataIndex: '合计',
					width: 120,
					readonly: true,
				})
				setColumns(column)
			})
			.catch((err) => {
				setColumns([])
				message.error(err)
			})
	}

	useEffect(() => {
		onCompany()
		onInCompany()
	}, [props?.user?.orgId])

	// 根据路由判断当前页面状态
	useEffect(() => {
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
			setEditableRowKeys(undefined)
		} else if (hrefs.includes('edit')) {
			setType('edit')
		}
	}, [])
	useEffect(() => {
		if (query?.id) {
			onCost()
			allocationnoInfo(query?.id).then((res: any) => {
				if (res?.success) {
					setDetailsData(res?.data)
					if (res?.data?.allocationStatus === 1) {
						setStatus('调拨中')
					}
					if (res?.data?.allocationStatus === 2) {
						setStatus('已完成')
					}
					if (res?.data?.allocationStatus === 3) {
						setStatus('已取消')
					}
					if (res?.data?.allocationStatus === 3) {
						cancelForm.setFieldsValue({...res.data})
					}
					const urls = res.data?.uploadFile
						?.split(',')
						.concat(res.data?.costFile?.split(','))
					const newData: any = {
						key: (Math.random() * 1000000).toFixed(0),
						项目: '金额/元',
					}
					res?.data?.costList?.forEach(
						(item: {costName: string | number; amount: any}) => {
							newData[item?.costName] = item.amount
						},
					)
					const hrefs = window.location.href
					if (hrefs.includes('edit')) {
						setEditableRowKeys([newData.key])
					}
					setCostData([{...newData}])
					getPublicDownloadUrl(urls)
						.then((result: any) => {
							const uploadFileUrls: any[] = []
							const costFileUrls: any[] = []
							result?.data?.forEach((item: any) => {
								const urlData = {
									uid: item?.id?.toString(),
									name: item?.filename,
									url: item?.url,
								}
								if (item?.targetAttr === 1) {
									uploadFileUrls.push(urlData)
								} else {
									costFileUrls.push(urlData)
								}
							})
							setFileList(costFileUrls)
							basicsForm.setFieldsValue({
								...res.data,
								uploadFile: uploadFileUrls,
							})
							costForm.setFieldsValue({
								costRemarks: res?.data?.costRemarks,
								costFile: costFileUrls,
							})
						})
						.catch((err: any) => {
							message.error(err)
						})
				}
			})
		}
	}, [query])

	const onSave = async () => {
		const costFile = fileList?.map(
			(item) => item?.response?.data?.id || item?.uid,
		)
		const costValue = await costForm.validateFields()
		if (costValue) {
			setFormData({
				...detailsData,
				...costValue,
				costFile: costFile.toString(),
				costList,
			})
			setIsModalOpen(true)
		}
	}
	const onSubmit = () => {
		setBtnLoading(true)
		editAllocationno({...formData, id: query.id})
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
				setBtnLoading(false)
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}
	const normFile = (e: any) => {
		if (Array.isArray(e)) {
			return e
		}
		return e?.fileList
	}
	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'storage_allocation',
			targetAttr: 2,
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				setFileList(info?.fileList)
			}
		},
		fileList,
	}

	return (
		<div className={styles.edit}>
			<div className={styles.title}>
				调拨发起信息
				<span>
					调拨批次：{detailsData?.allocationCode}({status})
				</span>
			</div>
			<Form
				className={styles.basicsForm}
				form={basicsForm}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '140px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off"
				disabled>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调出公司名称"
							name="orgId"
							rules={[{required: true}]}>
							<TreeSelect
								style={{width: '100%'}}
								fieldNames={fieldNames}
								treeDataSimpleMode
								treeData={companyData}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调入公司名称"
							name="moveInCompany"
							rules={[{required: true}]}>
							<TreeSelect
								style={{width: '100%'}}
								fieldNames={fieldNames}
								treeDataSimpleMode
								treeData={inCompanyData}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调出城市"
							name="moveOutCityName"
							rules={[{required: true}]}>
							<Input disabled />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调入城市"
							name="moveInCityName"
							rules={[{required: true}]}>
							<Input disabled />
						</Form.Item>
					</Col>
					<Col span={18}>
						<Form.Item label="备注" name="remarks">
							<TextArea
								maxLength={200}
								placeholder={
									type === 'view'
										? '-'
										: '请输入（最多200个字）'
								}
								autoSize={{minRows: 1, maxRows: 6}}
							/>
						</Form.Item>
					</Col>
					<Col span={24}>
						<Form.Item
							name="uploadFile"
							label="调拨附件"
							valuePropName="fileList"
							getValueFromEvent={normFile}
							rules={[
								{required: true, message: '请上传调拨附件'},
							]}
							className={styles.fileUpload}>
							<Upload {...uploadProps} />
						</Form.Item>
					</Col>
				</Row>
			</Form>
			<AllocateVehicles
				companyId={detailsData?.orgId}
				allocationId={query?.id}
			/>

			{detailsData?.allocationStatus === 3 ? (
				<>
					<div className={styles.title}>取消原因</div>
					<Form
						form={cancelForm}
						name="cancel"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled>
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 8}}>
								<Form.Item label="取消人员" name="cancelPerson">
									<Input placeholder="请输入" disabled />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 8}}>
								<Form.Item label="取消时间" name="cancelTime">
									<Input placeholder="请输入" disabled />
								</Form.Item>
							</Col>
							<Col span={18}>
								<Form.Item label="取消原因" name="cancelReason">
									<TextArea
										maxLength={200}
										placeholder="请输入（最多200个字）"
										autoSize={{minRows: 1, maxRows: 6}}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</>
			) : (
				''
			)}
			{detailsData?.costFile || type === 'edit' ? (
				<>
					{' '}
					<div className={styles.title}>调拨费用项信息</div>
					{costData && (
						<EditableProTable<any>
							className={styles.costTable}
							bordered
							rowKey="key"
							recordCreatorProps={false}
							columns={columns}
							value={costData}
							onChange={setCostData}
							editable={{
								form,
								editableKeys,
								onSave: async () => true,
								onChange: setEditableRowKeys,
								actionRender: (row, config, dom) => [
									dom.save,
									dom.cancel,
								],
							}}
						/>
					)}
					<Form
						form={costForm}
						name="cost"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled={type === 'view'}>
						<Row gutter={12}>
							<Col span={18}>
								<Form.Item label="备注" name="costRemarks">
									<TextArea
										maxLength={200}
										placeholder={
											type === 'view'
												? '-'
												: '请输入（最多200个字）'
										}
										autoSize={{minRows: 3, maxRows: 6}}
									/>
								</Form.Item>
							</Col>
							<Col span={24}>
								<Form.Item
									name="costFile"
									label="费用项附件"
									valuePropName="fileList"
									getValueFromEvent={normFile}
									rules={[
										{
											required: true,
											message: '请上传费用项附件',
										},
									]}
									className={styles.fileUpload}>
									<Upload {...uploadProps}>
										{fileList.length >= 3 ||
										type === 'view' ? null : (
											<Button>请选择文件</Button>
										)}
									</Upload>
								</Form.Item>
								<div className={styles.uploadTip}>
									附件说明：附件最大支持20M，支持格式：PDF、Word、Excel、JPG、PNG
								</div>
							</Col>
						</Row>
					</Form>
				</>
			) : (
				''
			)}
			{type === 'view' ? (
				<>
					<div className={styles.title}>操作记录</div>
					<OperationRecord businessId={query?.id} businessType={38} />
				</>
			) : (
				''
			)}

			<div className={styles.wrap}>
				{type === 'view' ? (
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						返回
					</Button>
				) : (
					<>
						<Button
							type="primary"
							htmlType="submit"
							onClick={() => {
								onSave()
							}}>
							保存
						</Button>
						<Button
							onClick={() => {
								history.go(-1)
							}}>
							取消
						</Button>
					</>
				)}
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				onSubmit={onSubmit}
				loading={btnLoading}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(edit)
